package com.fita.wechat.web.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.handler.CookieHandler;
import com.demo2do.core.web.utils.WebUtils;
import com.demo2do.core.wechat.entity.cfg.JsConfig;
import com.fita.wechat.Constant;
import com.fita.wechat.handler.SmsHandler;
import com.fita.wechat.processor.WechatProcessor;
import com.fita.wechat.service.AgentService;
import com.fita.wechat.web.interceptor.Wechat;
/**
 * 
 * @author sjh
 *
 */
@Controller
public class LoginController {
    
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    
    @Autowired
    private AgentService agentService;
    
    @Autowired
    private SmsHandler smsHandler;
    
    @Autowired
    private CookieHandler cookieHandler;
    
    @Autowired
    private WechatProcessor wechatProcessor;
    
    /**
     * 
     * @param request
     * @return
     */
    @Wechat
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request,
                              @RequestParam(required = false, name = "redirectUrl") String redirectUrl,
                              Long primaryAgentId,
                              Long rate) {
        ModelAndView modelAndView = new ModelAndView("login");
        
        String curl = WebUtils.getRealRequestURL(request);

        JsConfig jsConfig = wechatProcessor.generateJsConfig(curl);

        modelAndView.addObject("jsConfig", JsonUtils.toJson(jsConfig));

        if (StringUtils.isNotBlank(redirectUrl)){
            modelAndView.addObject("redirectUrl", WebUtils.encode(redirectUrl));
        }
        if (primaryAgentId != null){
            modelAndView.addObject("primaryAgentId", primaryAgentId);
        }
        if (rate != null){
            modelAndView.addObject("rate", rate);
        }
        return modelAndView;
    }


    /**
     *
     * @param mobile
     * @param code
     * @param token
     * @param request
     * @param response
     * @param redirectUrl
     * @return
     */
    @Wechat
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public HttpResult onLogin(@RequestParam("mobile") String mobile,
                              @RequestParam("code") String code,
                              @RequestParam("token") String token, 
                              HttpServletRequest request, 
                              HttpServletResponse response,
                              @RequestParam(required = false, name = "redirectUrl") String redirectUrl) {
        
        HttpResult httpResult = new HttpResult();
        try {
            //check verify code first 
            boolean valid = smsHandler.checkVerifyCode(mobile, code, token);
            if(valid) {
                
                Cookie openidCookie = org.springframework.web.util.WebUtils.getCookie(request, Constant.OPENID_KEY);
                String openid = null;
                if(openidCookie != null) {
                    openid = openidCookie.getValue();
                }
                
                agentService.login(mobile, openid);
                cookieHandler.addCookie(response, Constant.MOBILE_KEY, mobile, 31*24*60*60);
                httpResult.success().message("登陆成功");
            }
            
        } catch (BusinessException e) {
            logger.error("LoginController#onLogin() error", e);
            httpResult.fail("500").message(e.getMessage());
        } catch (Exception e) {
            logger.error("LoginController#onLogin() error", e);
            httpResult.fail("500").message("登陆失败");
        }
        return httpResult;
        
    }

    /**
     * 登出
     * @param request
     * @param response
     * @return
     */
    @PostMapping(path = "/logout", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public HttpResult logout(HttpSession session, HttpServletRequest request, HttpServletResponse response){

        HttpResult httpResult = new HttpResult();

        session.invalidate();
        
        Cookie[] cookies = request.getCookies();

        for (Cookie cookie : cookies){
            cookieHandler.removeCookie(response, cookie.getName());
        }
        return httpResult.success();
    }

}
